<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="1200px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="isUpdate ? '修改工作流' : '添加工作流'"
    @update:visible="updateVisible"
  >
    <div style="margin-bottom: 20px">
      <el-steps :active="active" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="技术设置"></el-step>
        <el-step title="表单设置"></el-step>
      </el-steps>
    </div>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <div v-if="active == 0">
        <el-form-item label="工作流名称:" prop="name">
          <el-input
            clearable
            v-model="form.name"
            placeholder="请输入工作流名称"
          />
        </el-form-item>

        <el-form-item label="封面:" prop="img">
          <span slot="label">
            封面

            <el-tooltip placement="top">
              <div slot="content" >
                建议上传344px * 500px尺寸,或者等比例图片
              </div>

              <i class="el-icon-question" />
            </el-tooltip>
          </span>

          <!--<ele-image-upload v-model="img" :limit="1" :drag="true" :multiple="false"  @upload="onUpload" /> -->
          <div class="ele-image-upload-list">
            <div
              class="ele-image-upload-item ele-image-upload-button"
              @click="modalPicTap('dan', 'img', '图片')"
            >
              <div>
                <div tabindex="0" class="el-upload el-upload--text">
                  <div class="el-upload-dragger">
                    <i class="el-icon-plus ele-image-upload-icon"></i>
                  </div>
                  <div
                    class="ele-image-upload-item"
                    style="margin: 0 0 0 0"
                    v-if="form.img != ''"
                  >
                    <div class="el-image">
                      <img
                        :src="form.img"
                        width="100%"
                        height="100%"
                        class="el-image__inner"
                        style="object-fit: cover"
                      />
                    </div>
                    <div
                      class="ele-image-upload-close"
                      @click="handleRemove('img')"
                      ><i class="el-icon-close"></i
                    ></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="描述:" prop="desc">
          <tinymce-editor v-model="form.desc" :init="editorConfig" />
        </el-form-item>
        

        
      <el-form-item label="分类:" prop="class_id">
       
        <ele-table-select
        
          ref="select"
          clearable
          v-model="form.class_id"
          placeholder="请选择"
          value-key="id"
          label-key="name"
          :table-config="tableConfig"
          :popper-width="580"
        >
         
        </ele-table-select>

       
        
      </el-form-item>


        <el-form-item label="扣点:" prop="points">
          <el-input
            type="number"
            step="0.01"
            v-model="form.points"
            label="扣点"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="输出文件类型:" prop="output_file_type">
          <el-input
            clearable
            v-model="form.output_file_type"
            placeholder="例如:pdf,doc,txt"
          />
        </el-form-item>

        <el-form-item label="排序号:" prop="sort">
          <el-input-number
            :min="0"
            v-model="form.sort"
            placeholder="请输入排序号"
            controls-position="right"
            class="ele-fluid ele-text-left"
          />
        </el-form-item>

        <el-form-item label="展示状态:">
          <el-switch
            :active-value="1"
            :inactive-value="2"
            v-model="form.is_display"
          />
          <el-tooltip
            placement="top"
            content="选择不可见则前端页面不显示该数据"
          >
            <i
              class="el-icon-_question"
              style="vertical-align: middle; margin-left: 8px"
            ></i>
          </el-tooltip>
        </el-form-item>
      </div>

      <div v-if="active == 1">
        <el-form-item label="工作流id:" prop="work_id">
          <el-input
            clearable
            v-model="form.work_id"
            placeholder="请输入工作流id"
          />
        </el-form-item>

        <el-form-item label="认证模式:" prop="authorize_type">
          <el-radio-group v-model="form.authorize_type">
            <el-radio label="1" value="1"> 配置默认</el-radio>
            <el-radio label="2" value="2">个人访问令牌</el-radio>
            <el-radio label="3" value="3">oauth授权</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="API Token:"
          v-if="form.authorize_type == '2'"
          prop="api_token"
        >
          <el-input
            clearable
            v-model="form.api_token"
            placeholder="请输入Coze个人访问令牌"
          />
		  
        </el-form-item>

		
            <el-form-item label="到期时间:" prop="api_token_expires_in"   v-if="form.authorize_type == '2'">
                <el-date-picker
                        v-model="form.api_token_expires_in"
                        type="datetime"
						 value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期时间">
                </el-date-picker>
            </el-form-item>

        <el-form-item
          label="OAuth应用ID:"
          v-if="form.authorize_type == '3'"
          prop="aouth_application_id"
        >
          <el-input
            clearable
            v-model="form.aouth_application_id"
            placeholder="请输入OAuth应用ID"
          />
        </el-form-item>
        <el-form-item
          label="OAuth公钥ID:"
          v-if="form.authorize_type == '3'"
          prop="aouth_public_id"
        >
          <el-input
            clearable
            v-model="form.aouth_public_id"
            placeholder="请输入OAuth公钥ID"
          />
        </el-form-item>

        <el-form-item v-if="form.authorize_type == '3'" label="key文件:">
          <div class="el-upload__text">服务商的key证书文件</div>
          <el-upload
            class="upload-demo"
            ref="upload"
            drag
            :on-success="handleSuccess1"
            :http-request="handleHttpRequest1"
            :limit="1"
            :disabled="disabled"
            :beforeDelete="beforeDelete"
            accept=".pem"
            action=""
            :file-list="fileList"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text"
              >将文件拖到此处，或<em>点击上传</em></div
            >
          </el-upload>
          <span v-if="form.pem" style="color: #18b53c">已上传证书</span>
        </el-form-item>
      </div>

      <div v-if="active == 2">
        <div class="form-top">
          <div>表单控件配置</div>
          <el-button type="primary" @click="addFrom">添加控件</el-button>
        </div>

        <div class="display-fw-a">
          <div v-for="(item, index) in listForm" :key="index">
            <div
              :class="
                listForm.length == 1
                  ? 'fields-list'
                  : listForm.length == 2
                  ? 'fields-list-2'
                  : 'fields-list-3'
              "
            >
              <div class="field-item field-item-half">
                <div class="field-header">
                  <span>控件{{ index + 1 }}</span>
                  <div class="field-actions">
                    <button
                      @click="moveUp(index)"
                      aria-disabled="true"
                      type="button"
                      class="el-button el-button--small"
                      :class="
                        listForm.length > 1 && index > 0 ? '' : 'is-disabled'
                      "
                    >
                      <span class>上移</span>
                    </button>
                    <button
                      @click="moveDown(index)"
                      aria-disabled="true"
                      type="button"
                      class="el-button el-button--small"
                      :class="listForm.length > index + 1 ? '' : 'is-disabled'"
                    >
                      <span class>下移</span>
                    </button>
                    <button
                      @click="delFrom(index)"
                      aria-disabled="false"
                      type="button"
                      class="el-button el-button--danger el-button--small"
                    >
                      <span class>删除</span>
                    </button>
                  </div>
                </div>
                <div class="field-content">
                  <el-form-item label="控件名称:" prop="name">
                    <el-input
                      clearable
                      v-model="item.name"
                      placeholder="控件名称"
                    />
                  </el-form-item>
                  <el-form-item label="类型:">
                    <el-select
                      clearable
                      v-model="item.type"
                      placeholder="请选择"
                      class="ele-fluid"
                    >
                      <el-option label="文本" value="1" />
                      <el-option label="数字" value="2" />
                      <el-option label="日期" value="3" />
                      <el-option label="图片" value="4" />
                      <el-option label="选择器" value="5" />
                      <el-option label="富文本" value="6" />
                      <el-option label="音频选择器" value="7" />
                           <el-option label="视频选择器" value="8" />

                    </el-select>
                  </el-form-item>

                  <el-form-item label="参数名:" prop="field">
                    <el-input
                      clearable
                      v-model="item.field"
                      placeholder="参数名"
                    />
                  </el-form-item>

                  <el-form-item label="提示文字:" prop="desc">
                    <el-input
                      clearable
                      v-model="item.desc"
                      placeholder="提示文字"
                    />
                  </el-form-item>

                  <!-- <el-form-item label="是否必填:" prop="is_required">
                    <el-radio-group v-model="item.is_required">
                      <el-radio label="1" value="1">是</el-radio>
                      <el-radio label="2" value="2">否</el-radio>
                    </el-radio-group>
                  </el-form-item> -->

                  <el-form-item label="快捷输入:" prop="quick">
                    <el-input
                      clearable
                      v-model="item.quick"
                      placeholder="请输入快捷选项，用逗号分隔,如：选项1,选项2,选项3"
                    />
                  </el-form-item>

                  <!-- <el-input-number
                    :min="0"
                    v-model="item.name"
                    placeholder="请输入排序号"
                    controls-position="right"
                    class="ele-fluid ele-text-left"
                  /> -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消 </el-button>

      <el-button v-if="active > 0" type="primary" @click="previous"
        >上一步</el-button
      >

      <el-button v-if="active != 2" type="primary" @click="next"
        >下一步</el-button
      >
      <el-button
        v-if="active == 2"
        type="primary"
        :loading="loading"
        @click="save"
        >保存
      </el-button>
    </template>
    <uploadPictures
      :isChoice="isChoice"
      :visible.sync="modalPic"
      @getPic="getPic"
      :gridBtn="gridBtn"
      :gridPic="gridPic"
      :title="modalTitle"
    ></uploadPictures>
  </ele-modal>
</template>

<script>
import PagesSearch from '@/views/common/pages/pages-search';
import uploadPictures from '@/components/uploadPictures';
import EleImageUpload from 'ele-admin/es/ele-image-upload';
import TinymceEditor from '@/components/TinymceEditor';
import request from '@/utils/request';
import { add, intelligenceClass, update } from '@/api/intelligence';
import { getPages } from '@/api/layout';
import { name } from 'ele-admin/lib/ele-pro-table';
const DEFAULT_FORM = {
  id: 0,
  name: '',

  img: '',
  desc: '',
  points: 0,
  is_display: 0,
  output_file_type: '',
  sort: '',
  work_id: '',
  authorize_type: '1',
  api_token: '',
  aouth_application_id: '',
  aouth_public_id: '',
  class_id:'',
  widget_josn: [],
  token: '',
  pem: '',
  is_display: 1,
  sort: 0,
  api_token_expires_in:''

};

export default {
  name: 'BannerEdit',
  components: {
    PagesSearch,
    EleImageUpload,
    uploadPictures,
    TinymceEditor
  },
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    b_type: 0
  },
  computed: {
    templateType() {
      return this.$store.state.user.template_type;
    }
  },

  data() {
    return {
      modalTitle: '选择图片',
      modalPic: false,
      isChoice: '单选',
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8
      },
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12
      },
      // 表单数据
      form: {
        ...DEFAULT_FORM
      },
      // 表单验证规则
      rules: {
        title: []
      },

      //表单控件数组
      listForm: [],

      // 提交状态
      loading: false,
      disabled: false,
      // 是否是修改
      isUpdate: false,
      fileList: [],
      tableConfig: {
        datasource: ({ page, limit, where, order }) => {
          return intelligenceClass({
            display:1,
            ...where,
            ...order,
            page,
            limit
          });
        },
        columns: [
        
          {
            prop: 'name',
            label: '名称',
            showOverflowTooltip: true,
            minWidth: 110
            //slot: 'nickname'
          },
          {
            prop: 'id',
            label: 'id',
            showOverflowTooltip: true,
            minWidth: 110
          }
        ],
        rowClickChecked: true,
        rowClickCheckedIntelligent: false,
        toolkit: ['reload', 'columns'],
        size: 'small',
        toolStyle: {
          padding: '0 10px'
        }
      },

      active: 0,
      editorConfig: {
        height: 525,
        relative_urls: false,
        convert_urls: false,
        images_upload_handler: (blobInfo, success, error) => {
          const file = blobInfo.blob();
          // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
          const formData = new FormData();
          formData.append('file', file, file.name);
          request({
            url: '/common/uploadFile',
            method: 'post',
            data: formData,
            onUploadProgress: (e) => {
              // 文件上传进度回调
            }
          })
            .then((res) => {
              if (res.data.code === 0) {
                success(res.data.data.url);
              } else {
                error(res.data.message);
              }
            })
            .catch((e) => {
              error('exception');
            });
        }
      }
    };
  },
  methods: {
    //添加表单控件
    addFrom() {
      let obj = {
        name: '',
        type: '',
        field: '',
        desc: '',
        is_required: '1'
      };
      this.listForm.push(obj);
    },

    //删除表单控件
    delFrom(index) {
      this.listForm.splice(index, 1);
    },

    //表单控件上移
    moveUp(index) {
      let temp = this.listForm[index - 1];
      this.listForm[index - 1] = this.listForm[index];
      this.listForm[index] = temp;
      this.listForm.splice(1, 0);
     
    },

    //表单控件下移
    moveDown(index) {
      let temp = this.listForm[index + 1];
      this.listForm[index + 1] = this.listForm[index];
      this.listForm[index] = temp;
      this.listForm.splice(1, 0);
    
    },

    //上一步
    previous() {
      this.active--;
    },

    //下一步
    next() {
      this.active++;
    },

    search(where) {
      // debugger
      this.$refs.select.reload({
        where: where,
        page: 1
      });
    },
    // 选择图片
    modalPicTap(tit, picTit, openTitle) {
      this.modalTitle = openTitle;
      this.isChoice = tit === 'dan' ? '单选' : '多选';
      this.picTit = picTit;
      this.modalPic = true;
    },
    // 选中图片
    getPic(pc) {
      switch (this.picTit) {
        case 'img':
          this.form.img = pc.satt_dir;
          break;
        case 'background':
          this.form.background = pc.satt_dir;
          break;
      }
      this.modalPic = false;
    },
    //删除图片
    handleRemove(field) {
      this.form[field] = '';
    },
    onUpload(item) {
      item.status = 'uploading';
      const formData = new FormData();
      formData.append('file', item.file);
      request({
        url: '/common/uploadFile',
        method: 'post',
        data: formData,
        onUploadProgress: (e) => {
          // 文件上传进度回调
          if (e.lengthComputable) {
            item.progress = (e.loaded / e.total) * 100;
          }
        }
      })
        .then((res) => {
          if (res.data.code === 0) {
            item.status = 'done';
            item.url = res.data.data.url;
            // 如果你上传的不是图片格式, 建议将 url 字段作为缩略图, 再添加其它字段作为最后提交数据
            //item.url = res.data.data.thumbnail;  // 也可以不赋值 url 字段, 默认会显示为一个文件图标
            item.fileUrl = res.data.data.url;
          }
        })
        .catch((e) => {
          item.status = 'exception';
        });
    },
    beforeUpload() {},
    beforeDelete(elIndex) {
      let vm = this;
      return (file, name) => {
        let fileIndex = name.index;
      
        vm.fileList[elIndex].splice(fileIndex, 1);
      };
    },
    handleHttpRequest1(option) {
      //上传OSS
      try {
        const formData = new FormData();
        formData.append('file', option.file);
        formData.append('type', 'cert');
        request({
          url: '/common/uploadIntelligencePem',
          method: 'post',
          data: formData,
          onUploadProgress: (e) => {
            // 文件上传进度回调
            if (e.lengthComputable) {
              option.progress = (e.loaded / e.total) * 100;
            }
          }
        })
          .then((res) => {
            if (res.data.code === 0) {
              option.status = 'done';
           
              this.form.pem = res.data.data.file;
        
              // option.url = res.data.data.url;
              // 如果你上传的不是图片格式, 建议将 url 字段作为缩略图, 再添加其它字段作为最后提交数据
              //item.url = res.data.data.thumbnail;  // 也可以不赋值 url 字段, 默认会显示为一个文件图标
              //option.fileUrl = res.data.data.url;
            }
          })
          .catch((e) => {
            option.status = 'exception';
            this.disabled = false;
            option.onError('上传失败');
          });
      } catch (error) {
        console.error(error);
        this.disabled = false;
        option.onError('上传失败');
      }
    },
    handleHttpRequest2(option) {
      //上传OSS
      try {
        const formData = new FormData();
        formData.append('file', option.file);
        formData.append('type', 'key');
        request({
          url: '/common/uploadPem',
          method: 'post',
          data: formData,
          onUploadProgress: (e) => {
            // 文件上传进度回调
            if (e.lengthComputable) {
              option.progress = (e.loaded / e.total) * 100;
            }
          }
        })
          .then((res) => {
            if (res.data.code === 0) {
              option.status = 'done';
              this.form.pay_key = '2';
              // option.url = res.data.data.url;
              // 如果你上传的不是图片格式, 建议将 url 字段作为缩略图, 再添加其它字段作为最后提交数据
              //item.url = res.data.data.thumbnail;  // 也可以不赋值 url 字段, 默认会显示为一个文件图标
              //option.fileUrl = res.data.data.url;
            }
          })
          .catch((e) => {
            option.status = 'exception';
            this.disabled = false;
            option.onError('上传失败');
          });
      } catch (error) {
        console.error(error);
        this.disabled = false;
        option.onError('上传失败');
      }
    },
    handleSuccess1(response, file, fileList) {
      this.fileList = this.fileList.concat(fileList);
      this.form.pay_cert = '2';
    },
    handleSuccess2(response, file, fileList) {
      this.fileList = this.fileList.concat(fileList);
      this.form.pay_key = '2';
      debugger;
    },

    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }

        this.loading = true;

        this.listForm.forEach((item, j) => {
          this.form.widget_josn[j] = item;
        });
	
        const data = {
          ...this.form
        };

        data.b_type = this.b_type;

        const saveOrUpdata = this.isUpdate ? update : add;

        saveOrUpdata(data)
          .then((msg) => {
            this.loading = false;
            this.$message.success(msg);
            this.updateVisible(false);
            this.$emit('done', {
              b_type: this.b_type
            });
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }
  },
  watch: {
    visible(visible) {
      if (visible) {
        if (this.data) {
          this.$util.assignObject(this.form, {
            ...this.data
          });
          this.listForm = this.form.widget_josn;
       
          this.isUpdate = true;
        } else {
          this.isUpdate = false;
        }
      } else {
        this.$refs['form'].clearValidate();
        this.form = {
          ...DEFAULT_FORM
        };
      }
    }
  }
};
</script>